#include "base/core/os/debug.h"
#include "Script/ScriptMgr_CS.h"
#include "Common/Lib/GlobalScriptFunc.h"
#include "Common/Lib/TimeScriptFunc.h"
#include "Script/GlobalScriptFunc_CS.h"

#ifdef _MSC_VER
#pragma warning(disable:4100)
#endif

ScriptMgrCS::ScriptMgrCS()
    : m_script()
	, m_memoryPool()
{}

ScriptMgrCS::~ScriptMgrCS()
{}

bool ScriptMgrCS::Init()
{
    if (m_script.Init(false, NULL) != 0) 
	{
        LogErrPrint("[center server] script init fail");
        return false;
    }

    if (!_RegistScriptObject()) {
        LogErrPrint("[center server] regist script object fail");
        return false;
    }

    if (!_LoadBootScript()) {
        LogErrPrint("[center server] load boot script fail");
        return false;
    }

    return true;
}

bool ScriptMgrCS::UnInit()
{
    m_script.UnInit();
    return true;
}

bool ScriptMgrCS::Update(uint64_t tick)
{
    m_script.GarbageCollect(1);
    return true;
}

bool ScriptMgrCS::ResetScriptState(bool reload)
{
    m_script.Reset();
    if (reload) 
	{
        _RegistScriptObject();
        _LoadBootScript();
        m_script.GarbageCollect(-1);
    }
    return true;
}

bool ScriptMgrCS::ReloadScriptFile(const char* fileName)
{
    bool result = false;
    result = m_script.CallFuncVoid("ReloadFile", fileName);
    return result;
}

bool ScriptMgrCS::ReLoadScript()
{
    _LoadBootScript();
    m_script.GarbageCollect(-1);
    return true;
}

LuaScript* ScriptMgrCS::GetScript()
{
    return &m_script;
}

bool ScriptMgrCS::_LoadBootScript()
{
	m_script.LoadFile("./data/script/root.lua");
	m_script.CallFuncVoid("RootScript");
    return true;
}

bool ScriptMgrCS::_RegistScriptObject()
{
    lua_State* state = m_script.GetState();
    MMO_ASSERT(state);

    m_script.SetGlobal<int32_t>("MODULE_CENTERSERVER", 1);
    m_script.SetGlobal<std::string>("SERVER_NAME", "center");
	
	RegistGlobalScriptFunc(state);
	RegistTimeScriptFunc(state);

	RegistGlobalCSScriptFunc(state);

    return true;
}
